//网络请求类

class MUtil{
    request(param){

        return new Promise((resolve ,reject)=>{
            $.ajax({
                type:       param.type      ||'get',
                url :       param.url       ||'',
                dataType:   param.dataType  ||'json',
                data:       param.data      ||null,
                success:res=>{
                    //数据请求成功
                    if(res.status===0){
                        typeof resolve==='function' && resolve(res.data,res.msg)
                    }else if(res.status===10){
                        //用户未登录，强制登陆
                        this.doLogin();

                    }else{
                        //账号密码有误
                        typeof reject==='function' && reject(res.data||res.msg)
                    }
                },
                error:err=>{
                    typeof reject==='function' && reject(err.statusText);
                }
            })
        })

    }
    //跳转登陆
    doLogin(){
        //redirect当前页面地址
        window.location.href='/login?redirect='+encodeURIComponent(window.location.pathname)
    }

    //获取url参数
    getUrlParam(name){
        let queryString =window.location.search.split('?')[1] || '',
            reg         =new RegExp("(^|&)"+name+"=([^&]*)(&|$)"),
            result      =queryString.match(reg);
        return result? decodeURIComponent(result[2]):null;

    }

    //成功提示
    successTip(successMsg){
        alert(successMsg||'操作成功~')
    }

    //错误提示
    errorTips(errMsg){
        alert(errMsg||'好像哪里不对了~')
    }

    //储存
    setStorage(name,data){
        let dataType=typeof data;
        if(dataType==='object'){
            window.localStorage.setItem(name,JSON.stringify(data))
        }else if(['number','string','boolean'].indexOf(dataType)>=0){
            window.localStorage.setItem(name,data)
        }else {
            alert('该类型不能用于本地存储')
        }
    }
    //取出存储
    getStorage(name){
        let data =window.localStorage.getItem(name)
        if (data){
            return JSON.parse(data)
        } else {
            return ''
        }
    }

    //删除存储
    removeStorage(name){
        window.localStorage.removeItem(name)
    }


}
export  default  MUtil